//
//  CommunitySelectorViewController.m
//  YYZB
//
//  Created by 顾悦 on 16/3/21.
//
//

#import "CommunitySelectorViewController.h"

#import "CommunityWebService.h"

#import "LoadingView.h"
#import "ThemeColor.h"

@interface CommunitySelectorViewController ()

@property (nonatomic, weak) IBOutlet UISearchBar *searchBar;
@property (nonatomic, weak) IBOutlet UITableView *tableView;

@property (nonatomic, strong) CommunityWebService *communityWebService;

@property (nonatomic, strong) NSMutableArray<Community *> *items;
@property (nonatomic, strong) NSArray<Community *> *filteredItems;

@end

@implementation CommunitySelectorViewController

#pragma mark -

- (CommunityWebService *)communityWebService {
    if (!_communityWebService) {
        _communityWebService = CommunityWebService.new;
    }
    
    return _communityWebService;
}

- (NSMutableArray<Community *> *)items {
    if (!_items) {
        _items = NSMutableArray.new;
    }
    
    return _items;
}

- (NSArray<Community *> *)filteredItems {
    NSString *searchText = [self.searchBar.text uppercaseString];
    NSArray<Community *> *filteredResults = [self.items filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name CONTAINS %@ || namePY CONTAINS %@", searchText, searchText]];
    if (searchText.length <= 0) {
        filteredResults = self.items;
    }
    
    _filteredItems = filteredResults;
    
    return _filteredItems;
}

#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"切换小区";
    [LoadingView show];
    [self.communityWebService getCommunitiesByCityID:self.selectedItem.cityID pageNo:@"1" pageSize:@"10000" completionHanlder:^(NSArray *items, NSError *error) {
        [LoadingView dismiss];
        if (error) {
            [LoadingView showToast:[error localizedDescription]];
        } else {
            NSMutableArray<Community *> *communities = NSMutableArray.new;
            for (NSDictionary *i in items) {
                [communities addObject:[[Community alloc] initWithDictionary:i]];
            }
            self.items = communities;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate & DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 || indexPath.row == 3) {
        return 10.0;
    }
    else if (indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 4) {
        return 40.0;
    }
    else {
        return 55.0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5 + [self.filteredItems count];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row <= 4) {
        cell.separatorInset = UIEdgeInsetsZero;
        cell.layoutMargins = UIEdgeInsetsZero;
        cell.preservesSuperviewLayoutMargins = NO;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 || indexPath.row == 3) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dummyCell" forIndexPath:indexPath];
        cell.backgroundColor = [ThemeColor lightGrayBGColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.separatorInset = UIEdgeInsetsZero;
        return cell;
    } else if (indexPath.row == 1 || indexPath.row == 4) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"selectedCell" forIndexPath:indexPath];
        cell.textLabel.font = [UIFont systemFontOfSize:13.0];
        cell.textLabel.textColor = [UIColor grayColor];
        if (indexPath.row == 1) {
            cell.textLabel.text = @"当前地址";
        } else {
            cell.textLabel.text = @"附近地址";
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    } else if (indexPath.row == 2) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"selectedCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.text = self.selectedItem.name;
        cell.textLabel.textColor = [UIColor darkGrayColor];
        
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
        
        // Configure the cell...
        Community *i = self.filteredItems[indexPath.row - 5];
        cell.textLabel.text = i.name;
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.detailTextLabel.text = i.address;
        cell.detailTextLabel.textColor = [UIColor grayColor];
        if ([[i.ID lowercaseString] isEqualToString:[self.selectedItem.ID lowercaseString]]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row <= 4) {
        return;
    }
    for (UITableViewCell *cell in tableView.visibleCells) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    
    self.selectedItem = self.filteredItems[indexPath.row - 5];
    [tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    if (self.delegate) {
        [self.delegate selectorDidSelectCommunity:self.selectedItem];
    }
}

#pragma mark -

#pragma mark -

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self.tableView reloadData];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
